package cn.linstudy.mq;

import cn.linstudy.service.IOrderInfoService;
import cn.linstudy.service.ISeckillProductService;
import cn.linstudy.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description
 * @Author XiaoLin
 * @Date 2021/5/20 21:56
 */
@Component
@RocketMQMessageListener(
    consumerGroup = "MQSeckillListener",
    topic = MQConstant.ORDER_PEDDING_TOPIC
)
@Slf4j
public class MQSeckillOrderListener implements RocketMQListener<OrderMessage> {

  @Autowired
  ISeckillProductService iSeckillProductService;

  @Autowired
  RocketMQTemplate rocketMQTemplate;

  @Override
  public void onMessage(OrderMessage orderMessage) {
    log.info("进入下单队列");
    Long seckillId = orderMessage.getSeckillId();
    Integer time = orderMessage.getTime();
    String token = orderMessage.getToken();
    Long userPhone = orderMessage.getUserPhone();
    String tag = "";
    // 无论成功还是失败，这些值都是必须有的，在这里可以先设置
    OrderMQResult orderMQResult = new OrderMQResult();
    orderMQResult.setSeckillId(seckillId);
    orderMQResult.setTime(time);
    orderMQResult.setToken(token);
    try {
//      System.out.println(11/0);
      // 执行秒杀业务
      String orderNo = iSeckillProductService.doSeckill(seckillId, time, userPhone);
      // 如果执行成功,先将订单编号设置到MQResult中
      orderMQResult.setOrderNo(orderNo);
      // 再将标签的值设置为success
      tag = MQConstant.ORDER_RESULT_SUCCESS_TAG;

    }catch (Exception e){
     tag = MQConstant.ORDER_RESULT_FAIL_TAG;
     orderMQResult.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
     orderMQResult.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());
    }
    rocketMQTemplate.syncSend(MQConstant.ORDER_RESULT_TOPIC,orderMQResult);
    rocketMQTemplate.syncSend(MQConstant.CANCEL_SECKILL_OVER_SIGE_TOPIC,orderMQResult.getSeckillId());
  }
}
